const fs = require('fs')
const readline = require('readline')

// 重写manifest.json文件
exports.initManifest = (manifest, config, path) => {
	// 设置应用名称
	if (config.wxAppName) {
		manifest.name = config.wxAppName
	}
	if (config.appVersion) {
		// 设置版本名称
		manifest.versionName = config.appVersion
		// 设置版本号
		manifest.versionCode = config.appVersion.split('.').reduce((prev, item) => {
			return prev + item + '0'
		}, '')
	}

	//创建新的manifest.json的数据
	let data = config.manifestConfig || {}


	let newManifest = createManifestObj(manifest, data)

	// h5配置生成
	newManifest.h5.router = {
		base: `/h5/${config.sellerNo}/`,
		mode: "hash"
	}
	// h5高德地图配置
	newManifest.h5.sdkConfigs = {
		maps: {
			amap: {
				key: config.mapH5key || "",
				securityJsCode: config.mapH5key1 || "",
				serviceHost: ""
			}
		}
	}
	// app项目需要填入对应的商家编号
	let appProjects=['hyc','cqym','xc']
		
	if(appProjects.includes(config.sellerNo)){
		console.log('检测到该项目含有app,执行自动配置图标')
		// 判断改目录是否存在
		if(fs.existsSync(`./init/icons/${config.sellerNo}`)){
			// 图标配置
			newManifest['app-plus']['distribute']['icons'] = {
				"android": {
					"hdpi": `init/icons/${config.sellerNo}/20x20.png`,
					"xhdpi": `init/icons/${config.sellerNo}/96x96.png`,
					"xxhdpi": `init/icons/${config.sellerNo}/144x144.png`,
					"xxxhdpi": `init/icons/${config.sellerNo}/192x192.png`
				},
				"ios": {
					"appstore": `init/icons/${config.sellerNo}/1024x1024.png`,
					"ipad": {
						"app": `init/icons/${config.sellerNo}/76x76.png`,
						"app@2x": `init/icons/${config.sellerNo}/152x152.png`,
						"notification": `init/icons/${config.sellerNo}/20x20.png`,
						"notification@2x": `init/icons/${config.sellerNo}/40x40.png`,
						"proapp@2x": `init/icons/${config.sellerNo}/167x167.png`,
						"settings": `init/icons/${config.sellerNo}/29x29.png`,
						"settings@2x": `init/icons/${config.sellerNo}/58x58.png`,
						"spotlight": `init/icons/${config.sellerNo}/40x40.png`,
						"spotlight@2x": `init/icons/${config.sellerNo}/80x80.png`
					},
					"iphone": {
						"app@2x": `init/icons/${config.sellerNo}/120x120.png`,
						"app@3x": `init/icons/${config.sellerNo}/180x180.png`,
						"notification@2x": `init/icons/${config.sellerNo}/40x40.png`,
						"notification@3x": `init/icons/${config.sellerNo}/60x60.png`,
						"settings@2x": `init/icons/${config.sellerNo}/58x58.png`,
						"settings@3x": `init/icons/${config.sellerNo}/87x87.png`,
						"spotlight@2x": `init/icons/${config.sellerNo}/80x80.png`,
						"spotlight@3x": `init/icons/${config.sellerNo}/120x120.png`
					}
				}
			}
		}else{
			return console.log(`错误：生成manifest.json文件失败：APP项目图标生产失败，该目录/init/icons/${config.sellerNo}不存在`)
		}
	}
	
	// 微信支付分APP WXUniPlugin 插件配置
	if (config.wxAppId && config.universalLink) {
		newManifest['app-plus']['nativePlugins']['WXUniPlugin']['appid'] = config.wxAppId
		newManifest['app-plus']['nativePlugins']['WXUniPlugin']['universalLink'] = config.universalLink
		newManifest['app-plus']['nativePlugins']['WXUniPlugin']['NL_WX_APPID'] = config.wxAppId
	}

	// 是否添加 农行APP 插件配置
	if (config.isBankABCCaller) {
		newManifest['app-plus']['nativePlugins']['BankABCCaller'] = {
			"__plugin_info__" : {
				"name" : "BankABCCaller",
				"description" : "中国农业银行App支付",
				"platforms" : "Android",
				"url" : "",
				"android_package_name" : "",
				"ios_bundle_id" : "",
				"isCloud" : false,
				"bought" : -1,
				"pid" : "",
				"parameters" : {}
			}
		}
	}

	// console.log(newManifest)
	//将创建的manifest.json的数据写入文件
	fs.writeFile(path, JSON.stringify(newManifest), function(err) {
		if (!err) {
			console.log(`开始生成 ${newManifest.name}${newManifest.versionName} 的配置......`)
			console.log(`生成manifest.json文件成功`)
		}
	})
}
// 重写androidPrivacy.json文件
exports.initAndroidPrivacy = (config, path) => {
	let privacyPolicy = config.privacyPolicy
	let userAgreement = config.userAgreement
	let version = config.appVersion
	let data = {
		version,
		prompt: 'template',
		title: '用户服务协议和隐私政策',
		message: `请你务必审慎阅读、充分理解“用户服务协议”和“隐私政策”各条款，包括但不限于：为了更好的向你提供服务，我们需要收集你的设备标识、操作日志等信息用于分析、优化应用性能。<br/>　你可阅读<a href='${userAgreement}'>《用户服务协议》</a>和<a href='${privacyPolicy}'>《隐私政策》</a>了解详细信息。如果你同意，请点击下面按钮开始接受我们的服务。`,
		buttonAccept: '同意',
		buttonRefuse: '不同意并退出App',
		second: {
			title: '温馨提示',
			message: `进入应用前，你需先同意<a href='${userAgreement}'>《用户服务协议》</a>和<a href='${privacyPolicy}'>《隐私政策》</a>,否则将退出应用。`,
			buttonAccept: '同意并继续',
			buttonRefuse: '退出应用',
		},
	}

	fs.writeFile(path, JSON.stringify(data), function(err) {
		if (!err) {
			console.log(`生成androidPrivacy.json文件成功`)
		}
	})
}
// 重写sellerTabs.js文件
exports.initSellerTabs = (config, path) => {
	let globalObj = Object.assign({}, config)
	delete globalObj.manifestConfig
	globalObj = JSON.stringify(globalObj)
	var json = `
    export function sellerTabs(globalDatas) {
        let globalObj = ${globalObj};
        globalDatas = Object.assign(globalDatas, globalObj)
    }
    `
	fs.writeFile(path, json, function(err) {
		if (!err) {
			console.log(`生成SellerTabs.js文件成功`)
		}
	})
}

// 重写sellerTabs.js文件
exports.initGlobalData = (config, defaulGlobalData, path) => {

	let globalData = Object.assign({}, defaulGlobalData, config)
	if (globalData.manifestConfig) {
		delete globalData.manifestConfig
	}

	globalData = JSON.stringify(globalData)
	var json = `
  export default ${globalData}
  `
	fs.writeFile(path, json, function(err) {
		if (!err) {
			console.log(`生成globalData.js文件成功`)
		}
	})
}

// 全局初始化文件 根据终端获取配置信息
exports.init = (configList, callback) => {
	let projectNum = null
	const rl = readline.createInterface({
		input: process.stdin,
		output: process.stdout,
	})

	// 监听键入回车事件
	console.log('请选择你想要配置的项目并且输入编号后按回车键')
	for (let key in configList) {
		console.log(`${key}:${configList[key].wxAppName} - ${configList[key].appVersion}`)
	}


	rl.on('line', (str) => {
		// str即为输入的内容
		str = str.trim()
		if (projectNum) {

			if (str == 'y') {
				// 执行回调开始重写配置
				callback(configList[projectNum])
				rl.close()
			} else if (str == 'yy') {
				let config = configList[projectNum]
				let {
					devURL,
					devimgUrl,
					devuploadUrl,
					devmarketingUrl,
					devpointsMallUrl,
					devagreementUrl
				} = config
				if (devURL && devimgUrl && devuploadUrl && devmarketingUrl) {
					config.URL = devURL
					config.imgUrl = devimgUrl
					config.uploadUrl = devuploadUrl
					config.marketingUrl = devmarketingUrl
					config.pointsMallUrl = devpointsMallUrl
					config.agreementUrl = devagreementUrl

					// 2023-12-19 新增营销获客测试环境功能是否打开
					config.isOpenDev = true
					callback(config)
					rl.close()
				} else {
					console.log('错误：该项目测试环境变量配置错误或未配置')
					rl.close()
				}
			} else {
				console.log('取消重写')
				rl.close()
			}
			return
		}
		if (str && configList[str]) {
			console.log(
				`你输入的编号为${str}:${configList[str].wxAppName} - ${configList[str].appVersion} 确定重写配置输入y或yy`,
			)
			let tips = '未定义该地址,请定义后重试'
			console.log(`注：输入y,  正式环境,地址：${configList[str].URL || tips}`)
			console.log(`注：输入yy, 测试环境,地址：${configList[str].devURL || tips}`)

			projectNum = str
			rl.prompt()
		} else {
			console.log('请输入正确的编号')
			rl.close()
		}
		// 关闭逐行读取流 会触发关闭事件
	})
}

// 递归替换对象方法
const createManifestObj = (manifest, data) => {
	Object.keys(data).forEach((key) => {
		let type = Object.prototype.toString.call(manifest[key])

		if (manifest[key]) {
			if (type == '[object Object]' && JSON.stringify(manifest[key]) != '{}') {
				manifest[key] = createManifestObj(manifest[key], data[key])
			} else {
				manifest[key] = data[key]
			}
		} else {
			manifest[key] = data[key]
		}
	})
	return manifest
}